package com.zhouyu.exampleSpSource.config;

import com.zhouyu.commonapi.resbody.ResBody;
import com.zhouyu.commonapi.utils.JsonUtil;
import com.zhouyu.commonapi.utils.algorithm.AesAlgorithmUtil;
import com.zhouyu.commonapi.utils.algorithm.Encrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Description:返回的参数加密
 * @author zhouyu
 * @date 2020/9/3
 * @since 1.0.0
 */
@RestControllerAdvice(basePackages = "com.zhouyu.exampleSpSource.controller.descontroller")
public class EncryResponseBodyAdvice implements ResponseBodyAdvice {
    private Logger logger = LoggerFactory.getLogger(EncryResponseBodyAdvice.class);
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object bodyObj, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(methodParameter.getMethod().isAnnotationPresent(Encrypt.class)){
            if(bodyObj instanceof ResBody){
                ResBody resBody= (ResBody) bodyObj;
                Object data = resBody.getData();
                String jsonData = JsonUtil.object2Json(data);
                try {
                    String aesEncryptData = AesAlgorithmUtil.aesEncrypt(jsonData, "d86d7bab3d6ac01ad9dc6a897652f2d2");
                    resBody.setData(aesEncryptData);
                } catch (Exception e) {
                    logger.error("加密参数异常",e);
                }
            }
        }
        return bodyObj;
    }
}
